using Dapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.H;
using RBAC.Interstructrue.Base;
using static RBAC.ErrorCode.APIEnums;
namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.H
{
    
    public class GetSalesOrderListHandler : IRequestHandler<GetSalesOrderListCommand, APIResult<GetSalesOrderListDto>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        public GetSalesOrderListHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        public async Task<APIResult<GetSalesOrderListDto>> Handle(GetSalesOrderListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using var connection = _dbConnectionFactory.CreateConnection();
                
                // 构建查询条件
                var whereConditions = new List<string>();
                var parameters = new DynamicParameters();
                
                if (!string.IsNullOrEmpty(request.SalesOrderNumber))
                {
                    whereConditions.Add("so.OrderCode LIKE @SalesOrderNumber");
                    parameters.Add("@SalesOrderNumber", $"%{request.SalesOrderNumber}%");
                }
                
                if (!string.IsNullOrEmpty(request.MaterialCode))
                {
                    whereConditions.Add("m.MaterCode LIKE @MaterialCode");
                    parameters.Add("@MaterialCode", $"%{request.MaterialCode}%");
                }
                
                if (!string.IsNullOrEmpty(request.MaterialName))
                {
                    whereConditions.Add("m.MaterName LIKE @MaterialName");
                    parameters.Add("@MaterialName", $"%{request.MaterialName}%");
                }

                var whereClause = whereConditions.Count > 0 ? "WHERE " + string.Join(" AND ", whereConditions) : "";

                // 查询总数
                var countSql = $@"
                    SELECT COUNT(*)
                    FROM SalesOrder so
                    INNER JOIN SalesOrderDetail sod ON so.Id = sod.SalesOrderId
                    INNER JOIN Mater m ON sod.MaterId = m.Id
                    
                    {whereClause}";// INNER JOIN MaterType mt ON m.MaterTypeId = mt.Id

                var totalCount = await connection.ExecuteScalarAsync<int>(countSql, parameters);

                // 分页查询数据
                var offset = (request.PageIndex - 1) * request.PageSize;
                var dataSql = $@"
                    SELECT 
                        (@row_number:=@row_number + 1) as SerialNumber,
                        so.OrderCode as SalesOrderNumber,
                        m.MaterCode as MaterialCode,
                        m.MaterName as MaterialName,
                        m.ModelSpec as ModelSpecification,
                        m.Unit as MainUnit,
                        sod.Num as Quantity,
                        CASE 
                            WHEN m.Unit = '件' THEN sod.Num
                            ELSE 0
                        END as PieceCount,
                        sod.Remark as Remarks,
                        '查看' as Operation
                    FROM SalesOrder so
                    INNER JOIN SalesOrderDetail sod ON so.Id = sod.SalesOrderId
                    INNER JOIN Mater m ON sod.MaterId = m.Id
                    CROSS JOIN (SELECT @row_number := {offset}) as r
                   
                    {whereClause}
                    ORDER BY so.OrderCode, m.MaterCode
                    LIMIT @PageSize OFFSET @Offset";
                // INNER JOIN MaterType mt ON m.MaterTypeId = mt.Id
                parameters.Add("@Offset", offset);
                parameters.Add("@PageSize", request.PageSize);

                var items = await connection.QueryAsync<SalesOrderItemDto>(dataSql, parameters);

                var result = new GetSalesOrderListDto
                {
                    TotalCount = totalCount,
                    Items = items.ToList()
                };

                return new APIResult<GetSalesOrderListDto>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetSalesOrderListDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"查询销售订单列表失败: {ex.Message}",
                    Data = default
                };
            }
        }
    }
} 